package lion.common;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class BeanTool {

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static void list2Map(Map objContainer, Collection objList, String keyField) {
		try {
			for (Object aObj : objList) {
				String methodname = "get" + formatProperties(keyField);
				Method method = aObj.getClass().getMethod(methodname);
				Object keypropvalue = method.invoke(aObj);
				objContainer.put(keypropvalue, aObj);
			}
		} catch (Exception ex) {
			throw new RuntimeException(ex.getMessage());
		}
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Map listToMap(List list, String properties, Class mapclass) {
		try {
			Map hashmap = (Map) mapclass.newInstance();
			for (Iterator iter = list.iterator(); iter.hasNext();) {
				Object item = iter.next();
				Object key = getPropValue(item, properties);
				hashmap.put(key, item);
			}
			return hashmap;
		} catch (Exception ex) {
			throw new RuntimeException(ex.getMessage());
		}
	}

	@SuppressWarnings({ "rawtypes" })
	public static Map listToMap(List list, String keyPropertiesName) {
		return listToMap(list, keyPropertiesName, HashMap.class);
	}

	private static String formatProperties(String name) {
		if (name.length() > 1) {
			if (Character.isLowerCase(name.charAt(0))) {// 小写
				if (Character.isLowerCase(name.charAt(1))) {// 小写
					return String.valueOf(name.charAt(0)).toUpperCase() + name.substring(1);
				} else {
					return String.valueOf(name.charAt(0)).toLowerCase() + name.substring(1);
				}
			} else {
				return name;
			}
		}
		return String.valueOf(name.charAt(0)).toUpperCase();
	}

	public static Object getPropValue(Object obj, String properties) throws Exception {
		String methodname = "get" + formatProperties(properties);
		Method method = obj.getClass().getMethod(methodname);
		Object keypropvalue = method.invoke(obj);
		return keypropvalue;
	}

	public static String getStackTraceInfo() {
		StackTraceElement[] ste = new Throwable().getStackTrace();
		StringBuilder sb = new StringBuilder();
		for (StackTraceElement stackTraceElement : ste) {
			sb.append(stackTraceElement);
			sb.append("\n");
		}
		return sb.toString();
	}
	
	public static void main(String[] args) {
		
	}
	
}
